package bin_tree.leetcode;

/**
 * 二叉树转为字符串
 * @author yuisama
 * @date 2021/12/08 21:23
 **/
public class Num606 {
    StringBuilder sb = new StringBuilder();
    // "1(2(4))(3)"
    public String tree2str(TreeNode root) {
        if (root == null) {
            return "";
        }
        preOrder(root);
        return sb.toString();
    }
    private void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        // "1(2(4))(3)"
        sb.append(root.val);
        if (root.left != null) {
            sb.append("(");
            // 先序遍历左树
            preOrder(root.left);
            sb.append(")");
        }else {
            // 左空，判断右树是否为空
            if (root.right != null) {
                sb.append("()");
            }
        }
        if (root.right != null) {
            sb.append("(");
            preOrder(root.right);
            sb.append(")");
        }
    }
}